/*
 
Copyright Eric C. McCreath 2012  <ericm@cs.anu.edu.au>

This file is part of the clapper-webcam-recorder project.

clapper-webcam-recorder is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License,
or (at your option) any later version.

clapper-webcam-recorder is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with clapper-webcam-recorder.  If not, see <http://www.gnu.org/licenses/>.

 */



#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <math.h>

#include <pulse/simple.h>
#include <pulse/error.h>
#include <pulse/gccmacro.h>


#include "clapper.h"
#include "util.h"
#include "sound.h"


pa_simple *pas;
short readbuffer[READ];


void setuppulse() {
    static const pa_sample_spec ss = {
        .format = PA_SAMPLE_S16LE,
        .rate = 44100,
        .channels = 1
    };
 
    int error;
    if (!(pas = pa_simple_new(NULL, "clapperWebcamRecorder", PA_STREAM_RECORD, NULL, "record", &ss, NULL, NULL, &error))) { 
        fprintf(stderr, "problem creating pa_simple : %s\n", pa_strerror(error));
        exit(EXIT_FAILURE);
    }
}


void closepulse() {
    if (pas) pa_simple_free(pas);
}


// fill the readbuffer with audio data - this blocks
int pulseread() {
    int error; 
    return (pa_simple_read(pas, readbuffer, sizeof(readbuffer), &error));
}

void pulseflush() {
     int error; 
     pa_simple_flush (pas, &error);
}

double volumn() {
    int i = 0;
    float val;
    double sum = 0.0;
    for (i=0;i<READ;i++) {
        val = readbuffer[i]/32768.0f;
        sum += val*val;
    }
    return sqrt (sum/READ);
}

// obtain the latency - in us
pa_usec_t pulselatency() {
    int error;
    return pa_simple_get_latency(pas, &error);
}



